import datetime
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import render, redirect
from django.conf import settings


class Bugplatform(object):

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    """ 中间件 """

    def process_request(self, request):
        """
        如果用户已登录，则在request中赋值
        :param request:
        :return:
        """

        request.bug_platform = Bugplatform()

        user_id = request.session.get('user_id', 0)
        # print(user_id)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        # print(user_object)

        request.bug_platform.user = user_object
        # bug_platform_object.user = user_object     # 把当前用户信息封装到用户对象中
        # # 把值赋给bug_platform 在存在request
        # # bug_platform 当前用户
        # request.bug_platform = bug_platform_object

        #
        # 白名单；没有登录都可以访问
        """
        1，获取用户当前访问的url
        2，判断url是否是在白名单中，如果在可以继续正常访问，如果不在在在进行判断是否已登录
        """
        # request.path_info    # 获取用户当前访问的url
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return None
        # 检查用户是否登录，已登录继续，未登录则返回登录页面
        # 这样可以成功判断，但是没有登录首页都不能访问了
        if not request.bug_platform.user:
            return redirect('/login/')

        # 登录成功后，访问后台管理时，获取用户所拥有的价格策略【额度
        # 方式一；免费的额度在交易记录中存储
        # 获取当前用户id值最大的【就是最后一条数据】所拥有的额度
        _object = models.Transaction.objects.filter(user_id=user_id, status=2).order_by('-id').first()
        # print(_object)
        # 会有结束时间小于当前时间的情况，那么就是免费的
        # 判断是否过期
        current_datatime = datetime.datetime.now()
        # 必须存在结束时间并且小于当前时间才判断为过期
        if _object.end_datetime and _object.end_datetime < current_datatime:
            # 过期
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()
        # request.transaction = _object
        # 额度信息
        request.bug_platform.price_policy = _object.price_policy

        # bug_platform_object.price_policy = _object.price_policy
        # request.price_policy = _object.price_policy

        # 方式二；免费的存在配置文件中
        """
        # 获取当前用户id值最大的【就是最后一条数据】所拥有的额度
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()
        if not _object:
            # 没有购买
            request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        else:
            # 付费版
            if _object.end_datetime and _object.end_datetime < datetime.datetime.now():
                # 过期
                request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
            else:
                request.price_policy = _object.price_policy
        """

    def process_view(self, request, view, args, kwargs):
        # 判断url是否是manage开头，如果是则向下判断project_id 是否是自己创建 or 还是参与的
        # print(request.path_info + '123')
        # print(request.path_info.startswith('/manage/'))
        if not request.path_info.startswith('/manage/'):
            return
        # project_id 是否是自己创建 or 还是参与的

        # 拿到当前用户对象
        # request.bug_platform.user
        # 拿到当前用户id
        project_id = kwargs.get('project_id')
        # print(project_id)
        # 判断是否自己创建的
        project_object = models.Project.objects.filter(creator=request.bug_platform.user, id=project_id).first()
        if project_object:
            # 是我创建的项目，我就让它通过在判断是我参与的码
            request.bug_platform.project = project_object
            return
        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.bug_platform.user, project_id=project_id)
        if project_user_object:
            # 是我参与的项目
            request.bug_platform.project = project_user_object
            return

        return redirect('project_list')
